<template>
  <div id="detail">
    <span id="one_test"></span>
    <AnchorTag :title="title" @toTarget="toTarget" :active="active"></AnchorTag>
    <div class="content-wrapper">
      <div id="one" class="content">
        <BasicInfo :form="form"></BasicInfo>
        <span id="two_test"></span>
      </div>
      <div id="two" class="content">
        <TableCom :headers="orderHeaders" :params="params" :isOrders="true"></TableCom>
      </div>
    </div>
  </div>
</template>

<script>
import AnchorTag from "./anchorTag";
import TableCom from "./components/tableCom";
import BasicInfo from "./components/basicInfo";
import { orderHeaders } from "./config";
export default {
  components: {
    AnchorTag,
    BasicInfo,
    TableCom
  },
  data() {
    return {
      distance_one: 0,
      distance_two: 0,
      active: "#one",
      scrollIntoViewOptions: {
        block: "start",
        behavior: "smooth"
      },
      params:{},
      form:{}
    };
  },
  created() {
    this.params = {
      purchaseNo : this.$route.query.purchaseNo 
    }
    this.init()
  },
  mounted() {
    // 一次性计算赋值，减少滚动计算节点位置次数
    this.distance_one = document.querySelector("#one").offsetTop;
    this.distance_two = document.querySelector("#two").offsetTop - 123;
    this.$nextTick(function() {
      document
        .querySelector("#detail")
        .addEventListener("scroll", this.onScroll);
    });
    window.addEventListener("scroll", this.onScroll, true);
  },
  methods: {
    init(){
      this.$http(`/purchases/${this.$route.query.id}`).then(res => {
        this.form = res
      });
    },
    toTarget(target) {
      this.active = target;
      let toElement = document.querySelector(target + '_test')
      toElement.scrollIntoView(this.scrollIntoViewOptions)
    },
    onScroll() {
      const scrolled = document.documentElement.scrollTop
      if (scrolled < this.distance_one) {
        this.active = '#one'
      } else if (scrolled >= this.distance_one && scrolled < this.distance_two) {
        this.active = '#one'
      }else {
        this.active = '#two'
      }
    }
  },
  destroyed() {
    window.removeEventListener("scroll", this.onScroll, true);
  },
  computed: {
    title() {
      const query = this.$route.query;
      if (query.purchaseNo) {
        return `采购单编号：${query.purchaseNo}（${query.operationMode}）`;
      } else {
        return "";
      }
    },
    orderHeaders() {
      return orderHeaders;
    }
  }
};
</script>

<style lang="scss" scoped>
#one_test {
  position:absolute;
  top:-84px;
}
#two_test {
  position:absolute;
  bottom:180px;
}
.content-wrapper {
  padding: 0 10px;
  padding-top: 120px;
  .content {
    position: relative;
    background-color: #fff;
    margin-bottom: 20px;
  }
}
</style>
